﻿using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using Wedn.Core.Common;
using Wedn.Core.Entity;
using Wedn.Core.Utility;

namespace Wedn.Core.Service
{
    /// <summary>
    /// 用户管理类
    /// </summary>
    public class UserManager
    {
        private Wedn.Interface.DAL.IUser dao;
        /// <summary>
        /// 用户管理类构造函数
        /// </summary>
        /// <exception cref="未找到系统数据库访问组件"></exception>
        public UserManager()
        {
            //dao = new Wedn.DAL.MSSQL.UserDAO();
            dao = Wedn.Interface.DAOFactory.CreateUserDAOInstance();
            if (dao == null)
            {
                throw new System.Exception("缺失数据库访问组件!");
            }
        }
        /// <summary>
        /// 像用户信息表插入一行数据, 返回执行结果受影响行数
        /// </summary>
        /// <param name="user">要添加的用户对象</param>
        /// <returns>执行结果受影响行数</returns>
        public int Insert(User user)
        {
            return dao.Insert(user);
        }

        /// <summary>
        /// 根据用户ID删除用户表中的用户记录, 返回执行结果受影响行数
        /// </summary>
        /// <param name="id">要删除的用户ID</param>
        /// <returns>执行结果受影响行数</returns>
        public int Delete(int id)
        {
            return dao.Delete(id);
        }

        /// <summary>
        /// 根据用户ID数组删除用户表中的用户记录, 返回执行结果受影响行数
        /// </summary>
        /// <param name="ids">要删除的用户ID数组</param>
        /// <returns>执行结果受影响行数</returns>
        public int Delete(int[] ids)
        {
            return dao.Delete(ids);
        }

        /// <summary>
        /// 更新一个完整用户对象, 返回执行结果受影响行数
        /// </summary>
        /// <param name="user">更新的用户对象</param>
        /// <returns>执行结果受影响行数</returns>
        public int UpdateUser(User user)
        {
            return dao.UpdateUser(user);
        }

        /// <summary>
        /// 更新用户的个人信息, 返回执行结果受影响行数
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="nickname">更新的昵称(不更新则传入null)</param>
        /// <param name="email">更新的Email(不更新则传入null)</param>
        /// <param name="url">更新的网址(不更新则传入null)</param>
        /// <param name="avatar">更新的头像(不更新则传入null)</param>
        /// <returns>执行结果受影响行数</returns>
        public int UpdateInfo(int id, string nickname, string email, string url)
        {
            return dao.UpdateInfo(id, nickname, email, url);
        }

        /// <summary>
        /// 更新用户密码, 返回执行结果受影响行数
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="password">更新的密码</param>
        /// <returns>执行结果受影响行数</returns>
        public int UpdatePassword(int id, string password)
        {
            return dao.UpdatePassword(id, password);
        }

        /// <summary>
        /// 批量更新用户状态, 返回执行结果受影响行数
        /// </summary>
        /// <param name="ids">用户ID</param>
        /// <param name="status">更新的权限(0:正常, 1:待验证审核)</param>
        /// <returns>执行结果受影响行数</returns>
        public int UpdateStatus(int[] ids, int status)
        {
            return dao.UpdateStatus(ids, status);
        }

        /// <summary>
        /// 批量更新用户角色, 返回执行结果受影响行数
        /// </summary>
        /// <param name="ids">用户ID</param>
        /// <param name="role">更新的角色(0:管理员,1:撰写人,2:订阅者)</param>
        /// <returns>执行结果受影响行数</returns>
        public int UpdateRole(int[] ids, int role)
        {
            return dao.UpdateRole(ids, role);
        }

        /// <summary>
        /// 获取表中主键最大值, 返回主键最大值
        /// </summary>
        /// <returns>主键最大值</returns>
        public int GetMaxId()
        {
            return dao.SelectMaxId();
        }

        /// <summary>
        /// 判断用户名是否存在,如果存在则返回TRUE,否则返回FALSE
        /// </summary>
        /// <param name="userName">要判断的用户名</param>
        /// <returns>存在则返回TRUE,否则返回FALSE</returns>
        public bool ExistsUser(string userName)
        {
            return dao.Exists(userName);
        }

        /// <summary>
        /// 选取用户总数
        /// </summary>
        /// <returns>总数</returns>
        public int GetUsersCount(string where)
        {
            return dao.SelectUsersCount(where);
        }

        /// <summary>
        /// 选取用户信息表中所有用户信息, 返回对象集合, 如果不存在则返回空集合
        /// </summary>
        /// <returns>所有用户信息集合</returns>
        public List<User> GetUserList()
        {
            List<User> list = dao.SelectUserList();
            if (list == null)
                list = new List<User>();
            return list;
        }

        /// <summary>
        /// 根据各种检索条件选取用户信息表中所有用户信息, 返回用户对象集合, 如果不存在则返回空集合
        /// </summary>
        /// <param name="keyword">关键字(忽略该条件则传入null)</param>
        /// <param name="status">状态(忽略该条件则传入-1)</param>
        /// <param name="role">角色(忽略该条件则传入-1)</param>
        /// <param name="pageSize">页面大小(忽略该条件则传入-1)</param>
        /// <param name="pageIndex">页码(忽略该条件则传入-1)</param>
        /// <param name="orderField">排序字段(忽略该条件则传入null)</param>
        /// <param name="order">排序方式(1:升序(asc)|2:降序(desc))(忽略该条件则传入-1)</param>
        /// <param name="recordCount">返回查询到的记录数</param>
        /// <returns>所有满足条件的用户信息集合</returns>
        public List<User> GetUserList(string keyword, int status, int role, int pageSize, int pageIndex, string orderField, int order, out int recordCount)
        {
            List<User> list = dao.SelectUserList(keyword, status, role, pageSize, pageIndex, orderField, order, out recordCount);
            if (list == null)
                list = new List<User>();
            return list;
        }

        /// <summary>
        /// 根据用户ID获取用户信息表中用户信息对象, 返回用户信息对象, 不存在则返回NULL
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户信息对象, 不存在则返回NULL</returns>
        public User GetUser(int id)
        {
            return dao.SelectUser(id);
        }

        /// <summary>
        /// 根据用户ID获取用户信息表中用户信息对象, 返回用户信息对象, 不存在则返回NULL
        /// </summary>
        /// <param name="login">用户登录名</param>
        /// <returns>用户信息对象, 不存在则返回NULL</returns>
        public User GetUser(string login)
        {
            return dao.SelectUser(login);
        }
        //===================================================
        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="uid">用户登录名</param>
        /// <param name="pwd">用户密码</param>
        /// <param name="currentUser">当前用户</param>
        /// <returns>登录结果</returns>
        public LoginResult Login(string uid, string pwd, out User currentUser)
        {
            return Login(uid, pwd, out currentUser, false);
        }

        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="uid">用户登录名</param>
        /// <param name="pwd">用户密码</param>
        /// <param name="currentUser">当前用户</param>
        /// <returns>登录结果</returns>
        public LoginResult Login(string uid, string pwd, out User currentUser, bool isFromCookie)
        {
            currentUser = GetUser(uid.ToLower());
            if (currentUser == null)
            {
                return LoginResult.NonExistent;
            }
            else if (currentUser.Password == (isFromCookie ? pwd : StringHelper.Encrypt(pwd))) //cookie中密码是已经加密过后的
            {
                return LoginResult.Success;
            }
            else if (currentUser.Status == 1)
            {
                return LoginResult.Awaiting;
            }
            else
            {
                return LoginResult.PasswordError;
            }
        }

        /// <summary>
        /// 获取一个用户的加密信息字符串
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <returns>加密后的字符串</returns>
        public string GetEncryptUserInfo(User user)
        {
            string temp = string.Format("uid={0}&ulogin={1}&upwd={2}", user.Id, user.Login, user.Password);
            return StringHelper.EncryptCookie(temp);
        }
        /// <summary>
        /// 根据加密后的cookie解密出用户实体部分信息, 返回用户实体
        /// </summary>
        /// <param name="cookie">要解密的cookie</param>
        /// <returns>返回用户实体</returns>
        public User GetDecryptUserInfo(string cookie)
        {
            string temp = string.Empty;
            try
            {
                temp = StringHelper.DecryptCookie(cookie);
            }
            catch
            {
                return null;
                throw;
            }
            string[] infos = temp.Split('&');
            return new User()
            {
                Id = int.Parse(infos[0].Split('=')[1]),
                Login = infos[1].Split('=')[1],
                Password = infos[2].Split('=')[1]
            };
        }
    }
    /// <summary>
    /// 登录结果
    /// </summary>
    public enum LoginResult
    {
        /// <summary>
        /// 用户名不存在
        /// </summary>
        NonExistent,
        /// <summary>
        /// 密码错误
        /// </summary>
        PasswordError,
        /// <summary>
        /// 要求用户输入验证码
        /// </summary>
        NeedValidateCode,
        /// <summary>
        /// 用户等待审核
        /// </summary>
        Awaiting,
        /// <summary>
        /// 登录成功
        /// </summary>
        Success
    }
}
